/**
 * 商品详情页JavaScript
 */

// 商品详情页管理器
window.GoodsDetail = {
    // 商品数据
    goodsData: null,

    // 当前图片索引
    currentImageIndex: 0,

    // 图片列表
    imageList: [],

    // 初始化
    init(data) {
        this.goodsData = data || {};
        this.imageList = this.getImageList();
        this.currentImageIndex = 0;
        this.bindEvents();
        this.initTabs();
        this.initImageGallery();

        // 滚动到活动标签页
        this.scrollToActiveTab();
    },

    // 从DOM中获取图片列表
    getImageList() {
        const imageList = [];

        // 从缩略图列表中获取图片URL
        const thumbnails = document.querySelectorAll('.thumbnail-item img');
        if (thumbnails && thumbnails.length > 0) {
            thumbnails.forEach(img => {
                const src = img.getAttribute('data-src') || img.getAttribute('src');
                if (src) {
                    imageList.push(src);
                }
            });
        }

        // 如果没有找到缩略图，尝试从主图中获取
        if (imageList.length === 0) {
            const mainImage = document.querySelector('#main-image');
            if (mainImage) {
                const src = mainImage.getAttribute('data-src') || mainImage.getAttribute('src');
                if (src) {
                    imageList.push(src);
                }
            }
        }

        return imageList;
    },

    // 绑定事件
    bindEvents() {
        // 绑定全局函数
        window.buyNow = () => this.buyNow();
        window.addToFavorite = (goodsId) => this.addToFavorite(goodsId);
        window.toggleFavorite = (goodsId) => this.toggleFavorite(goodsId);
        window.showTab = (tabName) => this.showTab(tabName);
        window.shareGoods = (platform) => this.share(platform);
        window.previewContent = () => this.previewContent();
        window.purchaseGoods = () => this.purchaseGoods();
        window.showLoginModal = () => this.showLoginModal();
        window.loginAndBuy = () => this.loginAndBuy();
    },

    // 初始化标签页
    initTabs() {
        // 默认显示第一个标签页
        this.showTab('content');
    },

    // 滚动标签导航到活动标签
    scrollToActiveTab() {
        const tabContainer = document.querySelector('.tab-nav-container');
        const activeTab = document.querySelector('.tab-button.active');

        if (tabContainer && activeTab) {
            // 滚动到活动标签的位置
            const scrollLeft = activeTab.offsetLeft - (tabContainer.clientWidth / 2) + (activeTab.clientWidth / 2);
            tabContainer.scrollLeft = Math.max(0, scrollLeft);
        }
    },

    // 初始化图片画廊
    initImageGallery() {
        if (this.imageList.length > 0) {
            this.updateMainImage();
        }
    },

    // 上一张图片
    previousImage() {
        if (this.imageList.length <= 1) return;

        this.currentImageIndex = this.currentImageIndex > 0
            ? this.currentImageIndex - 1
            : this.imageList.length - 1;

        this.updateMainImage();
    },

    // 下一张图片
    nextImage() {
        if (this.imageList.length <= 1) return;

        this.currentImageIndex = this.currentImageIndex < this.imageList.length - 1
            ? this.currentImageIndex + 1
            : 0;

        this.updateMainImage();
    },

    // 更新主图
    updateMainImage() {
        const $mainImage = $('#main-image');
        const $imageIndex = $('#current-image-index');

        if (this.imageList.length > 0) {
            const currentImage = this.imageList[this.currentImageIndex];
            $mainImage.attr('src', currentImage);
            $mainImage.attr('data-src', currentImage);

            if ($imageIndex.length) {
                $imageIndex.text(this.currentImageIndex + 1);
            }
        }
    },

    // 打开图片查看器
    openImageViewer() {
        if (this.imageList.length === 0) return;

        // 如果有GLightbox，使用GLightbox
        if (typeof GLightbox !== 'undefined') {
            // 动态创建lightbox链接
            const lightboxHtml = this.imageList.map((image, index) =>
                `<a href="${image}" class="glightbox" data-gallery="goods-gallery" data-title="商品图片 ${index + 1}"></a>`
            ).join('');

            // 临时添加到页面
            const $tempContainer = $('<div style="display:none;">').html(lightboxHtml);
            $('body').append($tempContainer);

            // 初始化GLightbox
            const lightbox = GLightbox({
                selector: '.glightbox',
                startAt: this.currentImageIndex
            });

            // 打开lightbox
            lightbox.open();

            // 清理临时元素
            setTimeout(() => $tempContainer.remove(), 100);
        } else {
            // 降级方案：在新窗口打开图片
            const currentImage = this.imageList[this.currentImageIndex];
            window.open(currentImage, '_blank');
        }
    },
    
    // 显示标签页
    showTab(tabName) {
        // 隐藏所有标签页内容
        $('.tab-content').hide();
        $('.tab-button').removeClass('active border-blue-500 text-blue-600')
            .addClass('border-transparent text-gray-500');

        // 显示指定标签页
        $(`#${tabName}-tab`).show();
        $(`.tab-button[onclick="showTab('${tabName}')"]`)
            .addClass('active border-blue-500 text-blue-600')
            .removeClass('border-transparent text-gray-500');

        // 如果切换到评论标签，初始化评论组件
        if (tabName === 'reviews') {
            this.initCommentsComponent();
        }

        // 滚动到选中的标签
        const tabContainer = document.querySelector('.tab-nav-container');
        const selectedButton = document.querySelector(`[onclick="showTab('${tabName}')"]`);
        if (tabContainer && selectedButton) {
            const scrollLeft = selectedButton.offsetLeft - (tabContainer.clientWidth / 2) + (selectedButton.clientWidth / 2);
            tabContainer.scrollTo({
                left: Math.max(0, scrollLeft),
                behavior: 'smooth'
            });
        }
    },

    // 初始化评论组件
    initCommentsComponent() {
        // 确保comments.js已加载
        if (typeof CommentsManager === 'undefined') {
            console.error('CommentsManager未定义，请确保comments.js已加载');
            return;
        }

        // 如果评论组件已经初始化，则不需要重复初始化
        if (window.commentsManager) {
            return;
        }
    },

    // 立即购买
    buyNow() {
        // showWarning('请先登录后再购买', 2500);
        // 跳转到购买页面
        window.location.href = `/pay-${this.goodsData.id}`;
    },

    // 添加到收藏
    addToFavorite(goodsId) {
        $.ajax({
            url: '/user/addFavorite',
            type: 'POST',
            data: {
                goods_id: goodsId
            },
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    showSuccess('收藏成功', 2000);

                    // 更新收藏按钮状态
                    const $favoriteBtn = $(`[onclick="addToFavorite(${goodsId})"]`);
                    $favoriteBtn.html('<i class="fas fa-heart text-red-500 mr-2"></i>已收藏')
                        .removeClass('hover:text-red-500')
                        .addClass('text-red-500')
                        .prop('onclick', null);
                } else {
                    showError(response.msg || '收藏失败', 3000);
                }
            },
            error: () => {
                showError('网络连接失败', 3000);
            }
        });
    },

    // 切换收藏状态
    toggleFavorite(goodsId) {
        // 检查登录状态
        if (!window.userState || !window.userState.isLogin) {
            showWarning('请先登录后再收藏', 2500);
            return;
        }

        // 检查当前收藏状态
        const $favoriteBtn = $(`[onclick*="toggleFavorite(${goodsId})"]`);
        const $icon = $favoriteBtn.find('i');
        const isFavorited = $icon.hasClass('fas') || $favoriteBtn.hasClass('text-red-500');

        if (isFavorited) {
            this.removeFavoriteToggle(goodsId);
        } else {
            this.addToFavoriteToggle(goodsId);
        }
    },

    // 添加收藏（用于toggle）
    addToFavoriteToggle(goodsId) {
        $.ajax({
            url: '/web/user/toggleFavorite',
            type: 'POST',
            data: {
                goods_id: goodsId
            },
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    const message = response.data && response.data.is_favorited ? '收藏成功' : '取消收藏成功';
                    showSuccess(message, 2000);

                    // 更新收藏按钮状态
                    const $favoriteBtn = $(`[onclick*="toggleFavorite(${goodsId})"]`);
                    const $icon = $favoriteBtn.find('i');

                    if (response.data && response.data.is_favorited) {
                        // 已收藏状态
                        $icon.removeClass('far').addClass('fas');
                        $favoriteBtn.removeClass('border-gray-300 text-gray-500 hover:border-red-400  hover:text-red-500')
                                   .addClass('border-red-400 bg-red-50 text-red-500 ');
                    } else {
                        // 未收藏状态
                        $icon.removeClass('fas').addClass('far');
                        $favoriteBtn.removeClass('border-red-400 bg-red-50 text-red-500 ')
                                   .addClass('border-gray-300 text-gray-500 hover:border-red-400  hover:text-red-500');
                    }
                } else {
                    showError(response.msg || '操作失败', 3000);
                }
            },
            error: () => {
                showError('网络连接失败', 3000);
            }
        });
    },

    // 取消收藏（用于toggle）
    removeFavoriteToggle(goodsId) {
        $.ajax({
            url: '/web/user/toggleFavorite',
            type: 'POST',
            data: {
                goods_id: goodsId
            },
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    const message = response.data && response.data.is_favorited ? '收藏成功' : '取消收藏成功';
                    showSuccess(message, 2000);

                    // 更新收藏按钮状态
                    const $favoriteBtn = $(`[onclick*="toggleFavorite(${goodsId})"]`);
                    const $icon = $favoriteBtn.find('i');

                    if (response.data && response.data.is_favorited) {
                        // 已收藏状态
                        $icon.removeClass('far').addClass('fas');
                        $favoriteBtn.removeClass('border-gray-300 text-gray-500 hover:border-red-400 hover:bg-red-50 hover:text-red-500')
                                   .addClass('border-red-400 bg-red-50 text-red-500 hover:bg-red-100');
                    } else {
                        // 未收藏状态
                        $icon.removeClass('fas').addClass('far');
                        $favoriteBtn.removeClass('border-red-400 bg-red-50 text-red-500 hover:bg-red-100')
                                   .addClass('border-gray-300 text-gray-500 hover:border-red-400 hover:bg-red-50 hover:text-red-500');
                    }
                } else {
                    showError(response.msg || '操作失败', 3000);
                }
            },
            error: () => {
                showError('网络连接失败', 3000);
            }
        });
    },

    // 取消收藏（兼容旧方法）
    removeFavorite(goodsId) {
        this.removeFavoriteToggle(goodsId);
    },

    // 分享功能
    share(platform) {
        if (!platform) {
            // 显示分享选项弹窗
            this.showShareModal();
            return;
        }

        const url = encodeURIComponent(window.location.href);
        const title = encodeURIComponent(this.goodsData.name || document.title);

        let shareUrl = '';

        switch (platform) {
            case 'weibo':
                shareUrl = `https://service.weibo.com/share/share.php?url=${url}&title=${title}`;
                break;
            case 'qq':
                shareUrl = `https://connect.qq.com/widget/shareqq/index.html?url=${url}&title=${title}`;
                break;
            case 'wechat':
                // 微信分享需要特殊处理
                showInfo('请复制链接到微信分享', 3000);
                this.copyToClipboard(window.location.href);
                return;
            case 'poster':
                // 生成分享海报
                this.generateSharePoster();
                return;
            case 'copy':
                // 复制链接
                this.copyToClipboard(window.location.href);
                return;
            default:
                showError('不支持的分享平台', 2000);
                return;
        }

        window.open(shareUrl, '_blank', 'width=600,height=400');
    },

    // 显示分享选项弹窗
    showShareModal() {
        const modalHtml = `
            <div id="share-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onclick="this.remove()">
                <div class="bg-white rounded-lg p-6 max-w-sm w-full mx-4" onclick="event.stopPropagation()">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">分享商品</h3>
                        <button onclick="document.getElementById('share-modal').remove()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <button onclick="GoodsDetail.share('poster')" class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <i class="fas fa-image text-2xl text-blue-500 mb-2"></i>
                            <span class="text-sm text-gray-700">生成海报</span>
                        </button>
                        <button onclick="GoodsDetail.share('copy')" class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <i class="fas fa-link text-2xl text-green-500 mb-2"></i>
                            <span class="text-sm text-gray-700">复制链接</span>
                        </button>
                        <button onclick="GoodsDetail.share('wechat')" class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <i class="fab fa-weixin text-2xl text-green-600 mb-2"></i>
                            <span class="text-sm text-gray-700">微信</span>
                        </button>
                        <button onclick="GoodsDetail.share('qq')" class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <i class="fab fa-qq text-2xl text-blue-600 mb-2"></i>
                            <span class="text-sm text-gray-700">QQ</span>
                        </button>
                        <button onclick="GoodsDetail.share('weibo')" class="flex flex-col items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <i class="fab fa-weibo text-2xl text-red-500 mb-2"></i>
                            <span class="text-sm text-gray-700">微博</span>
                        </button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);
        // 关闭分享弹窗
        setTimeout(() => {
            $('#share-modal').on('click', function(e) {
                if (e.target === this) {
                    $(this).remove();
                }
            });
        }, 100);
    },

    // 生成分享海报
    generateSharePoster() {
        // 关闭分享弹窗
        $('#share-modal').remove();

        // 显示生成中提示
        showInfo('正在生成分享海报...', 2000);

        // 创建海报容器
        const posterHtml = `
            <div id="poster-modal" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50" onclick="this.remove()">
                <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4" onclick="event.stopPropagation()">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">分享海报</h3>
                        <button onclick="document.getElementById('poster-modal').remove()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div id="poster-container" class="mb-4">
                        <canvas id="poster-canvas" width="400" height="600" class="w-full border border-gray-200 rounded-lg"></canvas>
                    </div>
                    <div class="flex space-x-3">
                        <button onclick="GoodsDetail.downloadPoster()" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors">
                            <i class="fas fa-download mr-2"></i>下载海报
                        </button>
                        <button onclick="GoodsDetail.copyPosterToClipboard()" class="flex-1 bg-green-500 text-white py-2 px-4 rounded-lg hover:bg-green-600 transition-colors">
                            <i class="fas fa-copy mr-2"></i>复制图片
                        </button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(posterHtml);

        // 生成海报
        setTimeout(() => {
            this.drawPoster();
        }, 100);
    },

    // 复制到剪贴板
    copyToClipboard(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(() => {
                showSuccess('链接已复制到剪贴板', 2000);
            }).catch(() => {
                this.fallbackCopyToClipboard(text);
            });
        } else {
            this.fallbackCopyToClipboard(text);
        }
    },

    // 降级复制方法
    fallbackCopyToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('copy');
            showSuccess('链接已复制到剪贴板', 2000);
        } catch (err) {
            showError('复制失败，请手动复制', 3000);
        }

        document.body.removeChild(textArea);
    },

    // 绘制海报
    drawPoster() {
        const canvas = document.getElementById('poster-canvas');
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        const goods = this.goodsData;

        // 设置画布尺寸
        canvas.width = 400;
        canvas.height = 600;

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制背景渐变
        const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
        gradient.addColorStop(0, '#f8fafc');
        gradient.addColorStop(1, '#e2e8f0');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制商品图片
        if (goods.image) {
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = () => {
                // 绘制商品图片 (居中，保持比例)
                const imgWidth = 300;
                const imgHeight = 200;
                const imgX = (canvas.width - imgWidth) / 2;
                const imgY = 40;

                ctx.drawImage(img, imgX, imgY, imgWidth, imgHeight);

                // 继续绘制其他内容
                this.drawPosterContent(ctx, goods);
            };
            img.onerror = () => {
                // 如果图片加载失败，直接绘制其他内容
                this.drawPosterContent(ctx, goods);
            };
            img.src = goods.image;
        } else {
            // 没有图片，直接绘制其他内容
            this.drawPosterContent(ctx, goods);
        }
    },

    // 绘制海报内容
    drawPosterContent(ctx, goods) {
        const canvas = ctx.canvas;

        // 绘制商品标题
        ctx.fillStyle = '#1f2937';
        ctx.font = 'bold 20px Arial, sans-serif';
        ctx.textAlign = 'center';

        // 处理长标题换行
        const title = goods.name || '商品名称';
        const maxWidth = 350;
        const lineHeight = 30;
        const lines = this.wrapText(ctx, title, maxWidth);

        let titleY = 280;
        lines.forEach((line, index) => {
            ctx.fillText(line, canvas.width / 2, titleY + (index * lineHeight));
        });

        // 绘制价格
        const priceY = titleY + (lines.length * lineHeight) + 40;
        if (goods.price && goods.price !== '0.00') {
            ctx.fillStyle = '#dc2626';
            ctx.font = 'bold 24px Arial, sans-serif';
            ctx.fillText(`¥${goods.price}`, canvas.width / 2, priceY);
        } else {
            ctx.fillStyle = '#059669';
            ctx.font = 'bold 24px Arial, sans-serif';
            ctx.fillText('免费', canvas.width / 2, priceY);
        }

        // 绘制网站信息
        const siteY = priceY + 60;
        ctx.fillStyle = '#6b7280';
        ctx.font = '14px Arial, sans-serif';
        ctx.fillText(window.location.hostname, canvas.width / 2, siteY);

        // 绘制二维码区域背景
        const qrY = siteY + 40;
        const qrSize = 120;
        const qrX = (canvas.width - qrSize) / 2;

        ctx.fillStyle = '#ffffff';
        ctx.fillRect(qrX - 10, qrY - 10, qrSize + 20, qrSize + 20);
        ctx.strokeStyle = '#e5e7eb';
        ctx.lineWidth = 1;
        ctx.strokeRect(qrX - 10, qrY - 10, qrSize + 20, qrSize + 20);

        // 绘制二维码占位符
        ctx.fillStyle = '#f3f4f6';
        ctx.fillRect(qrX, qrY, qrSize, qrSize);

        // 绘制二维码中心图标
        ctx.fillStyle = '#9ca3af';
        ctx.font = '40px FontAwesome';
        ctx.fillText('📱', canvas.width / 2, qrY + qrSize / 2 + 15);

        // 绘制提示文字
        ctx.fillStyle = '#6b7280';
        ctx.font = '12px Arial, sans-serif';
        ctx.fillText('扫码查看详情', canvas.width / 2, qrY + qrSize + 30);

        // 尝试生成真实的二维码
        this.generateQRCode(window.location.href, qrX, qrY, qrSize);
    },

    // 文本换行处理
    wrapText(ctx, text, maxWidth) {
        const words = text.split('');
        const lines = [];
        let currentLine = '';

        for (let i = 0; i < words.length; i++) {
            const testLine = currentLine + words[i];
            const metrics = ctx.measureText(testLine);
            const testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                lines.push(currentLine);
                currentLine = words[i];
            } else {
                currentLine = testLine;
            }
        }
        lines.push(currentLine);

        return lines.slice(0, 3); // 最多显示3行
    },

    // 生成二维码
    generateQRCode(text, x, y, size) {
        // 如果有QRCode库，使用它生成二维码
        if (typeof QRCode !== 'undefined') {
            const canvas = document.getElementById('poster-canvas');
            const ctx = canvas.getContext('2d');

            // 创建临时canvas用于生成二维码
            const tempCanvas = document.createElement('canvas');
            const qr = new QRCode(tempCanvas, {
                text: text,
                width: size,
                height: size,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.M
            });

            // 等待二维码生成完成
            setTimeout(() => {
                const qrImg = tempCanvas.querySelector('img');
                if (qrImg) {
                    ctx.drawImage(qrImg, x, y, size, size);
                }
            }, 100);
        }
    },

    // 下载海报
    downloadPoster() {
        const canvas = document.getElementById('poster-canvas');
        if (!canvas) return;

        try {
            const link = document.createElement('a');
            link.download = `${this.goodsData.name || '商品'}_分享海报.png`;
            link.href = canvas.toDataURL('image/png');
            link.click();
            showSuccess('海报下载成功', 2000);
        } catch (err) {
            showError('下载失败，请重试', 3000);
        }
    },

    // 复制海报到剪贴板
    copyPosterToClipboard() {
        const canvas = document.getElementById('poster-canvas');
        if (!canvas) return;

        try {
            canvas.toBlob((blob) => {
                if (navigator.clipboard && navigator.clipboard.write) {
                    const item = new ClipboardItem({ 'image/png': blob });
                    navigator.clipboard.write([item]).then(() => {
                        showSuccess('海报已复制到剪贴板', 2000);
                    }).catch(() => {
                        showError('复制失败，请使用下载功能', 3000);
                    });
                } else {
                    showError('浏览器不支持复制图片，请使用下载功能', 3000);
                }
            }, 'image/png');
        } catch (err) {
            showError('复制失败，请使用下载功能', 3000);
        }
    },

    // 显示登录弹窗
    showLoginModal() {
        if (typeof openLoginModal === 'function') {
            openLoginModal(window.location.pathname);
        } else {
            window.location.href = '/user/login?redirect=' + encodeURIComponent(window.location.pathname);
        }
    },

    // 登录后购买
    loginAndBuy() {
        if (typeof openLoginModal === 'function') {
            // 立即弹出登录弹窗，无toast提示
            const currentUrl = window.location.pathname;
            openLoginModal(currentUrl);
        } else {
            // 降级方案：跳转到登录页
            const redirectUrl = encodeURIComponent(window.location.href);
            window.location.href = `/user/login?redirect=${redirectUrl}`;
        }
    }
};

// 全局函数，供模板调用
function showTab(tabName) {
    GoodsDetail.showTab(tabName);
}

function buyNow() {
    GoodsDetail.buyNow();
}

function loginThenBuy() {
    GoodsDetail.loginAndBuy();
}

function toggleFavorite(goodsId) {
    GoodsDetail.toggleFavorite(goodsId);
}

function addToFavorite(goodsId) {
    GoodsDetail.addToFavorite(goodsId);
}

function shareGoods(platform) {
    GoodsDetail.share(platform);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 从DOM属性中获取商品数据
    const mainContainer = document.querySelector('[data-goods-id]');
    if (!mainContainer) {
        console.error('无法找到商品容器');
        return;
    }

    // 提取必要的商品数据
    const goodsData = {
        id: parseInt(mainContainer.getAttribute('data-goods-id')) || 0,
        name: mainContainer.getAttribute('data-goods-name') || '',
        price: parseFloat(mainContainer.getAttribute('data-goods-price')) || 0,
        has_paid: mainContainer.getAttribute('data-goods-has-paid') === '1',
        paid_content_type: mainContainer.getAttribute('data-goods-paid-content-type') || '',
        // 其他必要的数据可以按需添加
    };

    // 初始化商品详情页
    if (typeof GoodsDetail !== 'undefined') {
        GoodsDetail.init(goodsData);
    }
});
